package com.yyy.tcc.service.compensation;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class RejectionDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
            10,                       // 核心线程数
            500,                      // 最大线程数
            60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(50000), // 队列容量10000
                new ThreadFactory() {    // 线程工厂
                    private final AtomicInteger threadNumber = new AtomicInteger(1);
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "transfer-thread-" + threadNumber.getAndIncrement());
                        t.setDaemon(true);
                        return t;
                    }
                },
            new ThreadPoolExecutor.CallerRunsPolicy()  // 调用者运行策略
        );

        // 模拟10万并发请求
        for (int i = 0; i < 100000; i++) {
            final int taskId = i;
            try {
                executor.execute(() -> {
                    try {
                        // 任务执行逻辑
                        System.out.println("Task-" + taskId +
                            " executed by " + Thread.currentThread().getName());
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            } catch (RejectedExecutionException e) {
                // 被拒绝的任务会在这里直接执行
                // 一旦进入这个分支，任务就会在当前线程（main）中执行
                // 不会再有机会进入线程池队列
                Runnable task = () -> {
                    try {
                        System.out.println("Rejected Task-" + taskId +
                            " executed by main thread");
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                };
                task.run();  // 直接在main线程中执行
            }
        }
    }
}
